home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
FM Towns: Free Software Collection 7
/
FM Towns Free Software Collection 7.iso
/
ms_dos
/
thmake
/
thcal.c
< prev
next >
Wrap
C/C++ Source or Header
|
1993-11-30
|
2KB
|
121 lines
/*
雪辱の逆襲戦い“THcal”
By 五味(93/06/17~93/07/14)
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define TRUE 0
#define FALSE -1
#define FULL (void *)0xffff
#define ENZ 5
char *mark[]={ "*","/","+","-","^","EOM" };
char mpri[]= { 20, 20, 30, 30, 10, 99 };
char *eos;
int isc;
int expr(char *,int,int);
int prex(char *,int);
int prex(char *siki,int enz)
{
char *p,k;
int tval;
for( ; *siki==' ' || *siki=='\t' ; siki++ );
if( *siki=='(' ) {
for( p=(++siki),k=1 ; k>0 ; p++ )
if( *p=='(' ) k++;
else if( *p==')' ) k--;
else if( *p=='\0') {
printf(" 括弧が異常です.\n");
exit(1);
}
*(p-1)='\0';
tval=prex(siki,ENZ);
if( p>eos ) eos=p;
siki=p;
}else{
tval=atoi(siki++);
for( ; isdigit(*siki) ; siki++ );
if( siki>eos ) eos=siki;
}
tval=expr(siki,enz,tval);
while( isc ) {
isc=0;
tval=expr(eos,enz,tval);
}
return tval;
}
int expr(char *siki,int enz,int tval)
{
int i; /* 汎用(ループ等) */
int enzk; /* 掛かっている演算子 */
int val; /* 一時的な値 */
char *lesp,*tmp; /* 演算子のポインタ */
for( i=0,enzk=ENZ,lesp=FULL ; i<ENZ ; i++ ) {
if( (tmp=strstr(siki,mark[i]))!=NULL && tmp<lesp ) {
lesp=tmp;
enzk=i;
} /* 後ろの演算子を割り出す */
}
if( enzk!=ENZ && mpri[enzk]<mpri[enz] ) { /* 演算子ごとの演算 */
val=prex(lesp+strlen(mark[enzk]),enzk);
switch(enzk) {
case 0: val=tval*val;
break;
case 1: val=tval/val;
break;
case 2: val=tval+val;
break;
case 3: val=tval-val;
break;
case 4: for( i=val,val=1 ; i>0 ; i-- )
val=val*tval;
break;
}
isc=1;
}else{
val=tval;
}
return val;
}
int calc(char *str)
{
isc=0;
return prex(eos=strdup(str),ENZ);
}
void main(int argc,char *argv[])
{
if( argc==1 ) {
printf( " 'THcal' 簡易計算機 v1.0a\n"
" (c) H.gomi 1993/07/14\n" );
return;
}
if( argc>2 ) {
printf(" 式に空白は挟めません.\n");
return;
}
printf( "\n"
"\t'%s'=%d\n",argv[1],calc(argv[1]) );
}